package com.ys.controller.web.business;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bo.dto.NameValueSelectDto;
import com.ys.entity.business.TpDeptUserPoint;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.sys.TsOrganizationInfo;
import com.ys.entity.sys.TsUserInfo;
import com.ys.entity.sys.YsCol;
import com.ys.entity.sys.YsMenu;
import com.ys.service.business.TpDeptUserPointService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.util.SnowflakeIdWorker;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

import lombok.AllArgsConstructor;
import lombok.Data;

@Controller
@RequestMapping("/web/business/tpDeptUserPoint")
public class WebTpDeptUserPointController {

	private static Long MENU_ID = 53L;

	@Autowired
	private CommonApiService<TpDeptUserPoint> commonApiService;
	@Autowired
	private TpDeptUserPointService tpDeptUserPointService;

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TpDeptUserPoint setSeachSql(TpDeptUserPoint cond){
        cond.addField("U.UserId + '/' + U.UserName AS pointUser ");//评价员工
        cond.addField("B.OrgName AS pointDept ");//评价部门
        cond.addField("U.DeptId ");//评价部门ID
        cond.addField("U2.UserId + '/' + U2.UserName AS createUserInfo ");//制单人
        cond.addField("U2.DeptName AS creatUserDept ");//制单人部门
        cond.addField("U2.DeptId AS creatUserDeptId ");//制单人部门ID
        cond.addField("P.VGsJc AS operateCompanyName ");//运营公司简称
		cond.addField("CASE WHEN A.EffectStock =0 THEN '否' ELSE '是' END isEffectStock ");//是否生效
        cond.addLeftJoin("TS_UserInfo U ON A.PointUserId = U.UserId ");
        cond.addLeftJoin("TS_UserInfo U2 ON A.CreateUser = U2.UserId ");
        cond.addLeftJoin("THR_OperateCompanyApply P ON A.OperateCompanyCode = P.VGsBm ");
        cond.addLeftJoin("TS_OrganizationInfo B on B.Orgid = A.PointDeptCode");
        return cond;
    }

	/**
	 * 获取部门评价列表信息
	 */
	@RequestMapping("/getDeptPointList")
	@ResponseBody
	public LayuiTableVoJA getDeptPointList(Model model, HttpServletRequest request, HttpServletResponse response,
										  @ModelAttribute TpDeptUserPoint cond,
										  String conditions,String guidTsOrganizationInfo
	){
        cond = setSeachSql(cond);
		//部门树的查询
		if (guidTsOrganizationInfo != null) {
			TsOrganizationInfo tsOrganizationInfo = new TsOrganizationInfo().setGuid(guidTsOrganizationInfo).queryFirst();
			cond.where("B.NodeLft >= " + tsOrganizationInfo.getNodeLft())
					.where("B.NodeRgt <= " + tsOrganizationInfo.getNodeRgt());
		}

		cond.setOrderby("A.CreateTime DESC");//排序，新添加在前

		//获取数据
		LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
		return tableVoJA;
	}

	/**
	 * 新增
	 */
	@GetMapping("/toAdd")
	public String toAdd(Model model){

		// 获取单号
		SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
		String  bid = "BMPJ-" + idWorker.nextId();

		String loginUserId = ShiroUtils.getUserId();//登录的用户信息
		String loginUserName = ShiroUtils.getUserName();
		String loginDeptId = ShiroUtils.getDeptId();//登录的用户的部门信息
		String loginDeptName = ShiroUtils.getOrgName();

		//SELECT VGsBm,VGsJc FROM THR_OperateCompanyApply  WHERE CUser = '00024'
		String whereStr = "1=1";
		if(!loginUserId.equals("admin")){//非管理员的情况只能获取到自己的运营公司，管理员获取所有的运营公司信息
			whereStr = "CUser = '"+loginUserId+"'";
		}
		List<ThrOperateCompanyApply> operateCompanyArr = new ThrOperateCompanyApply()//运营公司信息(编码，简称)
				.where(whereStr)
				.queryList();
		//List<NameValueSelectDto> operateCompanyArr = new ArrayList<>();//运营公司信息(编码，简称)

		List<NameValueSelectDto> pointTypeArr = new ArrayList<>();//评价类别：0表扬，1批评
		pointTypeArr.add(new NameValueSelectDto("表扬", "0", false));
		pointTypeArr.add(new NameValueSelectDto("批评", "1", false));

		List<NameValueSelectDto> pointDeptArr = new ArrayList<>();//评价部门,评价员工

		String  createUserInfo = loginUserId+"/"+loginUserName;//制单人
		String  creatUserDept = loginDeptName;//制单人部门
		String  creatUserDeptId = loginDeptId;//制单人部门Id
		ToAddDto dto = new ToAddDto(bid, operateCompanyArr, pointTypeArr, pointDeptArr, createUserInfo,loginUserId,creatUserDept,creatUserDeptId);

		model.addAttribute("dto", dto);
		return "business/tpDeptUserPoint/toAdd";
	}

	/**
	 * 新增
	 */
    //@RequiresPermissions("tpDeptUserPoint:add")
	@PostMapping("/addDeptUserPoint")
	@ResponseBody
	public R addDeptUserPoint(HttpServletRequest request, @RequestParam Map<String, Object> params){
		try {
			return tpDeptUserPointService.add(params,MENU_ID);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}
	/**
	 * 修改、详情
	 */
	@GetMapping("/toDeptUserPointEditOrDetail")
	public String toDeptUserPointEditOrDetail(Model model,Long id,int type){

		Map entity = new TpDeptUserPoint().setId(id)
				.addField("U.UserId AS pointUserId ")//评价员工Id
				.addField("U.UserId + '/' + U.UserName AS pointUser ")//评价员工
				.addField("B.OrgName AS pointDept ")//评价部门
				.addField("U.DeptId ")//评价部门ID
				.addField("U2.UserId AS createUserId ")//制单人id
				.addField("U2.UserId + '/' + U2.UserName AS createUserInfo ")//制单人
				.addField("U2.DeptName AS creatUserDept ")//制单人部门
				.addField("U2.DeptId AS creatUserDeptId ")//制单人部门ID
				.addField("P.VGsJc AS operateCompanyName ")//运营公司简称
				.addField("B.NodeLft ")
				.addField("B.NodeRgt ")
				.addLeftJoin("TS_UserInfo U ON A.PointUserId = U.UserId ")
				.addLeftJoin("TS_UserInfo U2 ON A.CreateUser = U2.UserId ")
				.addLeftJoin("THR_OperateCompanyApply P ON A.OperateCompanyCode = P.VGsBm ")
				//.addLeftJoin("TS_OrganizationInfo B on B.Guid = U.Organizationid")
				.addLeftJoin("TS_OrganizationInfo B on B.Orgid = A.PointDeptCode")
				.queryFirstMap();
		// 获取单号
		String bid = entity.get("bid").toString();//单号
		String operateCompanyCode = entity.get("operateCompanyCode").toString();//运营公司编码
		String operateCompanyName = entity.get("operateCompanyName").toString();//运营公司简称
		String pointType = entity.get("pointType").toString();//评价类别：0表扬，1批评
		String pointDeptCode = entity.get("pointDeptCode").toString();//评价的部门的编码
		String pointDept = entity.get("pointDept").toString();//评价部门
		String PointUserId = entity.get("pointUserId").toString();//评价的员工的工号
		String pointUser = (entity.get("pointUser")==null?"":entity.get("pointUser").toString());//评价员工
		String pointEvent = entity.get("pointEvent").toString();//评价事件
		String PointDetail = (entity.get("pointDetail")==null?"":entity.get("pointDetail").toString());//评价详情
		String createUserInfo = entity.get("createUserInfo").toString();//制单人
		String creatUserDept = entity.get("creatUserDept").toString();//制单人部门
		String creatUserDeptId = entity.get("creatUserDeptId").toString();//制单人部门Id
		String loginUserId = entity.get("createUserId").toString();//登录的用户Id
		String NodeLft = entity.get("NodeLft").toString();
		String NodeRgt = entity.get("NodeRgt").toString();

		String whereStr = "1=1";
		if(!loginUserId.equals("admin")){//非管理员的情况只能获取到自己的运营公司，管理员获取所有的运营公司信息
			whereStr = "CUser = '"+loginUserId+"'";
		}
		List<ThrOperateCompanyApply> operateCompanyArr = new ThrOperateCompanyApply()//运营公司信息(编码，简称)
				.where(whereStr)
				.queryList();

		List<NameValueSelectDto> pointTypeArr = new ArrayList<>();//评价类别：0表扬，1批评
		pointTypeArr.add(new NameValueSelectDto("表扬", "0", (pointType.equals("0")?true:false)));
		pointTypeArr.add(new NameValueSelectDto("批评", "1", (pointType.equals("1")?true:false)));

		List<NameValueSelectDto> pointDeptArr = new ArrayList<>();//评价部门,评价员工

		String pathFlowPass = "/api/inter/tpDeptUserPoint/flowPassDeptUserPoint";
		String pathFlowRefuse = "/api/inter/tpDeptUserPoint/flowRefuse";
		String pathCommitDelete = "/api/inter/tpDeptUserPoint/deleteDeptUserPoint";
		YsMenu ysMenu = new YsMenu().setId(MENU_ID).queryFirst();
		//Map<String, Object> map = new TpDeptUserPoint().where("A.Id = '" + id + "'").queryFirstMap();

//		CommonApiService.ToFormDto.ButtonDto headerButton  = commonApiService.getHeaderForEdit(ysMenu,entity );
		CommonApiService.ToFormDto.ButtonDto headerButton  = null;
		ToEditDto dto = new ToEditDto(
				headerButton,id,bid, operateCompanyCode,operateCompanyName,pointType,pointDeptCode,pointDept,PointUserId,pointUser,pointEvent,PointDetail,
				createUserInfo,loginUserId,creatUserDept,creatUserDeptId,NodeLft,NodeRgt,operateCompanyArr, pointTypeArr, pointDeptArr,
				pathFlowPass,pathFlowRefuse,pathCommitDelete
		);

		model.addAttribute("dto", dto);
		if(type==1){//修改
			return "business/tpDeptUserPoint/toEdit";
		}else {//详情
			return "business/tpDeptUserPoint/toDetail";
		}

	}
	@Data
	@AllArgsConstructor
	private static class ToEditDto{
		private CommonApiService.ToFormDto.ButtonDto headerButton;
		private Long id;
		private String bid;
		private String operateCompanyCode;//运营公司编码
		private String operateCompanyName;//运营公司简称
		private String pointType;//评价类别：0表扬，1批评
		private String pointDeptCode;//评价的部门的编码
		private String pointDept;//评价部门
		private String PointUserId;//评价的员工的工号
		private String pointUser;//评价员工
		private String pointEvent;//评价事件
		private String PointDetail;//评价详情
		private String createUserInfo;
		private String loginUserId;
		private String creatUserDept;
		private String creatUserDeptId;
		private String NodeLft;
		private String NodeRgt;
		private List<ThrOperateCompanyApply> operateCompanyArr;
		private List<NameValueSelectDto> pointTypeArr;
		private List<NameValueSelectDto> pointDeptArr;
		private String pathFlowPass;
		private String pathFlowRefuse;
		private String pathCommitDelete;

	}
	/**
	 * 修改
	 */
	@RequiresPermissions("tpDeptUserPoint:edit")
	@PostMapping("/editDeptUserPoint")
	@ResponseBody
	public R editDeptUserPoint(HttpServletRequest request, @RequestParam Map<String, Object> params){
		return tpDeptUserPointService.edit(params);
	}

	@Data
	@AllArgsConstructor
	private static class ToAddDto{
		private String bid;
		private List<ThrOperateCompanyApply> operateCompanyArr;
		private List<NameValueSelectDto> pointTypeArr;
		private List<NameValueSelectDto> pointDeptArr;
		private String createUserInfo;
		private String loginUserId;
		private String creatUserDept;
		private String creatUserDeptId;
	}

	/**
	 * 选择评价员工页面
	 */
	@GetMapping("/toSelectorPointUser")
	public String toSelectorPointUser(Model model, HttpSession session, String nodeLft,String nodeRgt){
		session.setAttribute("nodeLft",nodeLft);
		session.setAttribute("nodeRgt",nodeRgt);
		return "business/tpDeptUserPoint/toSelectorPointUser";
	}

	/**
	 * 根据评价部门获取评价员工
	 */
	@RequestMapping("/getUserInfoByDept")
	@ResponseBody
	public LayuiTableVoJA getUserInfoByDept(Model model, HttpServletRequest request, HttpServletResponse response,
										   @RequestParam Map<String, Object> params, HttpSession session
	){
		String nodeLft = session.getAttribute("nodeLft").toString();
		String nodeRgt = session.getAttribute("nodeRgt").toString();
		//String nodeLft =params.get("nodeLft").toString();
		//String nodeRgt = params.get("nodeRgt").toString();
		//查询评价员工数据
		List<TsUserInfo> userList = new TsUserInfo()
				.addLeftJoin("TS_OrganizationInfo B on B.Guid = A.Organizationid")
				.where("B.NodeLft >= " + nodeLft)
				.where("B.NodeRgt <= " + nodeRgt)
				.queryList();

		LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
		tableVoJA.setCode(0);
		JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(userList));
		tableVoJA.setData(jsonArray);
		return tableVoJA;
	}

	//导出
	@RequestMapping("/exportTpDeptUserPoint")
	@ResponseBody
	public R exportTpDeptUserPoint(@ModelAttribute TpDeptUserPoint cond, String conditions) throws Exception {

		cond.setPage(0).setSize(999999);
        cond = setSeachSql(cond);
		cond.setOrderby("A.CreateTime DESC");//排序，新添加在前
		//获取数据
		List<Map<String, Object>> listData = cond.queryMap();
        List<YsCol> listField = new YsCol()
                .setMenuId(MENU_ID)
                .where("A.Code != 'ope'")
                .setOrderby("A.SortNo asc")
                .queryList();
		listField.add(new YsCol().setName("制单时间").setCode("createTime"));

		ExportExcelUtils<TpDeptUserPoint> util = new ExportExcelUtils<>(new TpDeptUserPoint());
        
        String toFilePath = util.exportExcel(listData, listField, "部门员工评价表");
        UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
	}


}



